package com.bi.onlineEducation.service;

import com.bi.onlineEducation.dao.PurchaseDao;
import com.bi.onlineEducation.domain.PurchasePo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: chenYuTao
 * @Time: 2022/1/19 23:41
 * @Description:
 **/
@Service
public class PurchaseService {
    @Resource
    private PurchaseDao purchaseDao;

    public List<PurchasePo> findAll() {
        return purchaseDao.findAll();
    }

    public PurchasePo findById(Integer id) {
        return purchaseDao.findById(id).get();
    }

    public PurchasePo save(PurchasePo purchasePo) {
        return purchaseDao.save(purchasePo);
    }

    public Boolean deleteById(Integer id) {
        purchaseDao.deleteById(id);
        return true;
    }

    @Transactional
    public Boolean deleteByIds(List<Integer> ids) {
        for (Integer id : ids) {
            purchaseDao.deleteById(id);
        }
        return true;
    }

    /**
     * 订单条件查询所有
     *
     * @param cName
     * @param address
     * @return
     */
    public List<PurchasePo> search(String cName, String address) {
        return getSearchPurchaseList(cName, address);
    }

    /**
     * 包含当前用户订单搜索
     *
     * @param cName
     * @param address
     * @param lId
     * @return
     */
    public List<PurchasePo> searchBylId(String cName, String address, Integer lId) {
        ArrayList<PurchasePo> resultList = new ArrayList<>();
        for (PurchasePo purchasePo : getSearchPurchaseList(cName, address)) {
            if (purchasePo.getLogin().getLId() != lId.intValue()) continue;
            resultList.add(purchasePo);
        }
        return resultList;
    }

    private ArrayList<PurchasePo> getSearchPurchaseList(String cName, String address) {
        List<PurchasePo> all = purchaseDao.findAll();
        ArrayList<PurchasePo> resultList = new ArrayList<>();
        ArrayList<PurchasePo> cNameList = new ArrayList<>();
        ArrayList<PurchasePo> addressList = new ArrayList<>();
        for (PurchasePo purchasePo : all) {
            if (StringUtils.isNotBlank(cName) && purchasePo.getCourse().getCName().indexOf(cName) > -1) {
                cNameList.add(purchasePo);
            }
            if (StringUtils.isNotBlank(address) && purchasePo.getLogin().getLAddress().indexOf(address) > -1) {
                addressList.add(purchasePo);
            }
        }
        if (StringUtils.isBlank(cName)) cNameList = (ArrayList<PurchasePo>) all;
        if (StringUtils.isBlank(address)) addressList = (ArrayList<PurchasePo>) all;
        for (PurchasePo realNameVo : cNameList) {
            for (PurchasePo addressVo : addressList) {
                if (realNameVo.getPId() != addressVo.getPId()) continue;
                resultList.add(realNameVo);
            }
        }
        return resultList;
    }
}
